<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google" value="notranslate">
    <title>vscode 自定义代码块</title>
    <style>
        button{
            margin: 10px 0;
        }
        textarea {
            width: 100%;
            height: 40vh;
            margin: 0 auto;
        }
    </style>
    <script>
        // 输入监听
        function inputChange() {
            let value = document.getElementById("inputCode").value;
            // 通过换行分割成数组
            let stringArray = value.split('\n');
            let outString = "";
            for (const row of stringArray) {
                if (row.trim() !== "") {
                    // ''替换"",\\$替换$
                    let tempRow = row.replace(/\"/g, "\'").replace(/\$/g, "\\\\$")
                    // 最后一个
                    outString = outString + "\"" + tempRow + "\"" + "," + "\n\t\t";
                }
            }
            outString = outString.substring(0, outString.length - 4);
            // 代码块对象
            let object = "\"snippets title\": {" +
                "\n\t\"prefix\": \"snippets prefix\"," +
                "\n\t\"body\": [" +
                "\n\t\t" + outString +
                "\n\t]," +
                "\n\t\"description\": \"snippets description\"" +
                "\n},";
            document.getElementById("outCode").innerHTML = object;
        }
        // 清空输入框
        function clearHandler(){
            document.getElementById("inputCode").value = "";
            document.getElementById("outCode").innerHTML = "";
        }
        // 复制结果
        function copyHandler() {
            var el = document.getElementById("outCode");
            var value = el.value;
            if (value === "") {
               return; 
            }
            el.select();
            document.execCommand("Copy");
            alert('复制成功');
        }
    </script>
</head>
<body>
    <button onclick="clearHandler()">清空输入</button>
    <textarea id="inputCode" placeholder="请粘贴需要自定义代码..." oninput="inputChange()"></textarea>
    <button onclick="copyHandler()">复制代码块</button>
    <label>把 snippets title、snippets prefix、snippets description 修改成代码块标题、代码块简写字符串、代码块描述</label>
    <textarea id="outCode"></textarea>
</body>

</html>